#include<iostream>
#include<string.h>
#include<unistd.h>
#include<netinet/in.h>
#include<sys/socket.h>
using namespace std;
#define PORT 8111
#define MESSAGE_LEN 1024

int main(){
        int socket_fd,accept_fd;
        int ret=-1;
        int on=1;
	pid_t pid;
        char in_buff[MESSAGE_LEN]={0,};
        struct sockaddr_in localaddr;
        struct sockaddr_in remoteaddr;
        int backlog=10;

        socket_fd=socket(AF_INET,SOCK_STREAM,0);// IPV4  TCP  0  create a socket
        if(socket_fd==-1){
                cout<<"failed to create socket!"<<endl;
                exit(-1);
        }

        ret=setsockopt(socket_fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //set socket option
        if(ret==-1){
                cout<<"failed to set socket option"<<endl;
        }

        localaddr.sin_family=AF_INET;
        localaddr.sin_port=PORT;
        localaddr.sin_addr.s_addr=INADDR_ANY;//INADDR_ANY==0
        bzero(&(localaddr.sin_zero),8);

        ret=bind(socket_fd,(struct sockaddr *)&localaddr,sizeof(struct sockaddr));
        if(ret==-1){
                cout<<"failed to bind addr and port!"<<endl;
                exit(-1);
        }

        ret=listen(socket_fd,backlog);
        if(ret==-1){
                cout<<"failed to listen!"<<endl;
                exit(-1);
        }

        for(;;){
             //create a new socket accept_fd
             socklen_t addr_len=sizeof(struct sockaddr);
             accept_fd=accept(socket_fd,(struct sockaddr *) &remoteaddr,&addr_len);// socket  client_ipAddress connected
	     
	     pid=fork();//let many client connect server by fork
	     if(pid==0){ //subprocess
             	for(;;){ //keeping receiving requests
                //client send data   read the received data into the in_buff
                	memset(in_buff,0,MESSAGE_LEN);
                	ret=recv(accept_fd,(void *)in_buff,MESSAGE_LEN,0);
                	if(ret==0){
                        	cout<<"client don't send data,disconnected"<<endl;
                        	break;
                	}
                	cout<<"recveived data is:"<<in_buff<<endl;
                	send(accept_fd,(void*)in_buff,MESSAGE_LEN,0);
             	}
                close(accept_fd);
	     }
        }
	if(pid!=0){
        	close(socket_fd);
	}
        return 0;
}
